#
# Handling of commands
#
from Client import Client
from Cache import Cache
import os
import pickle
import subprocess
import time
import StringIO

class Commands(object):

    cachename = '.cache-commands'

    def __init__(self):
        self.cache = Cache(os.path.join(os.path.expanduser(u'~'), '.fgs'))
        self.commands = {}
        self.load()
        self.process = None

    def load(self, force=False):
        if not force:
            try:
                if self.cache.has_file(self.cachename):
                    data = self.cache.retrieve_file(self.cachename, None)
                    strio = StringIO.StringIO(data)
                    self.commands = pickle.load(strio)
                    strio.close()
            except:
                force = True

        if force:
            self.commands = Client()._get_commands()
            strio = StringIO.StringIO()
            pickle.dump(self.commands, strio)
            self.cache.store_file(strio.getvalue())
            strio.close()

    def get_by_gid(self, gid):
        c = {}
        for k in self.commands:
            if self.commands[k]['game_gid'] == gid:
                c[len(c)] = self.commands[k]
        return c

    def is_running(self):
        if self.process:
            if self.process.poll() == None:
                return True
        return False

    def stop(self, force=False):
        if not self.is_running():
            return True

        pid = self.process.pid
        sig = ''

        if os.name == 'nt':
            if force:
                sig = '/F'
            subprocess.Popen('taskkill %s /PID %i' % (sig, pid), shell=True)

        elif os.name == 'posix':
            if force:
                sig = '-9'
            subprocess.Popen('kill %s %i' % (sig, pid), shell=True)

        time.sleep(1)

        return self.is_running()

    def transform(self, cmd, port=0):
        cmd = cmd.replace('{PATH}', '')
        cmd = cmd.replace('{HOST}', '127.0.0.1')
        cmd = cmd.replace('{PORT}', str(port))
        return cmd

    def start(self, cmd):
        self.process = subprocess.Popen(cmd, shell=True)
